namespace eval cache_categories {
#   {server1 {category1 type1} server2 {category2 type2}}
    custom::defvar category_and_subtype_list {} \
	[::msgcat::mc "Cached service categories and types (from disco#info)."] \
	-type string -group Hidden

    variable requested_categories
}

##############################################################################

proc cache_categories::fill_cached_categories_and_subtypes {connid} {
    variable category_and_subtype_list
    variable requested_categories

    catch { array set tmp $category_and_subtype_list }
    set requested_categories($connid) [array names tmp]
    foreach jid [array names tmp] {
	lassign $tmp($jid) category subtype
	roster::override_category_and_subtype $connid $jid \
					      $category $subtype
    }
}

hook::add connected_hook \
    [namespace current]::cache_categories::fill_cached_categories_and_subtypes 5

##############################################################################

proc cache_categories::free_cached_categories_and_subtypes {connid} {
    variable category_and_subtype_list
    variable requested_categories

    if {$connid == {}} {
	array unset requested_categories
    } else {
	catch { unset requested_categories($connid) }
    }
}

hook::add disconnected_hook \
    [namespace current]::cache_categories::free_cached_categories_and_subtypes

##############################################################################

proc cache_categories::request_category_and_subtype {connid jid} {
    variable category_and_subtype_list
    variable requested_categories

    set server [server_from_jid $jid]
    if {[lsearch -exact $requested_categories($connid) $server] >= 0} {
	return
    }

    lappend requested_categories($connid) $server

    jlib::send_iq get \
	[jlib::wrapper:createtag query \
	     -vars [list xmlns $::NS(disco_info)]] \
	-to $server \
	-connection $connid \
	-command [list [namespace current]::parse_requested_categories $connid $server]
}

##############################################################################

proc cache_categories::parse_requested_categories {connid server res child} {
    variable category_and_subtype_list

    if {$res != "OK"} return

    jlib::wrapper:splitxml $child tag vars isempty chdata children

    foreach ch $children {
	jlib::wrapper:splitxml $ch tag1 vars1 isempty1 chdata1 children1
	switch -- $tag1 {
	    identity {
		set category [jlib::wrapper:getattr $vars1 category]
		set type [jlib::wrapper:getattr $vars1 type]

		roster::override_category_and_subtype $connid $server \
						      $category $type
		lappend category_and_subtype_list \
			$server [list $category $type]

		::redraw_roster
		break
	    }
	}
    }
}

###############################################################################


